package com.ezjie.ielts.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioButton;

import com.ezjie.ielts.R;
import com.ezjie.ielts.util.DensityUtil;

public class UpAlignmentRiadioButton extends RadioButton {

	private Context mContext;

	public UpAlignmentRiadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		mContext = context;
	}

	public UpAlignmentRiadioButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;

	}

	public UpAlignmentRiadioButton(Context context) {
		super(context);
		mContext = context;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		setCompoundDrawables(mContext.getResources().getDrawable(R.drawable.radio_button), null, null, null);
		Drawable[] drawables = getCompoundDrawables();
		setCompoundDrawables(null, null, null, null);
		if (drawables != null) {
			Drawable drawableLeft = drawables[0];
			if (drawableLeft != null) {
				float textWidth = getPaint().measureText(getText().toString());
				int drawablePadding = getCompoundDrawablePadding();
				int drawableWidth = 0;
				drawableWidth = drawableLeft.getIntrinsicWidth();
				setPadding(drawableWidth + drawablePadding, getPaddingTop(), getPaddingRight(), getPaddingBottom());
				canvas.drawBitmap(drawableToBitmap(drawableLeft), 0, getPaddingTop() + DensityUtil.dip2px(mContext, 4),
						getPaint());
			}
		}
		super.onDraw(canvas);
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
				drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}
}
